// 弹出框组件
import { defineComponent, watch } from "vue";
import { ElTable, ElPagination } from "element-plus";
import tableCard from "./tableCard";
import "./index.scss";

// 继承element的ElTable 所有属性
const tableList = defineComponent({
	components: {
		tableCard
	},
	props: {
		data: {
			type: Array,
			default: () => {
				return [];
			}
		},
		rowClass: {
			type: String || Function,
			default: "table-row-style"
		},
		total: {
			type: Number,
			default: 10
		},
		pageSize: {
			type: Number,
			default: 10
		},
		pageIndex: {
			type: Number,
			default: 1
		},
		// 分页属性
		pagination: {
			type: Object,
			default: () => {
				return {
					background: true,
					layout: "total, prev, pager, next",
					small: true
				};
			}
		},
		// 选中事件
		selectionChange: {
			type: Function
		},
		// 模式 list 列表 card 卡片
		mode: {
			type: String,
			default: "list"
		},
		// card 模式专有
		column: {
			type: Array,
			default: () => {
				return [];
			}
		},
		// card 模式专有
		// 每行卡片数
		col: {
			type: Number
		},
		// card 模式专有
		setting: {
			type: Object
		},
		cardSlot: {
			type: Object
		}
	},
	emits: ["pageChange"],
	setup(props, { slots, attrs, emit }) {
		const tableRef = ref<any>();
		const selected = ref<any>([]);
		const data = reactive({
			pageSize: props.pageSize,
			pageIndex: props.pageIndex
		});
		watch(
			() => data.pageIndex || data.pageSize,
			() => {
				emit("pageChange", data.pageIndex, data.pageSize);
			}
		);
		const rowClick = (row: any) => {
			let checked = selected.value.find((item: any) => item.id == row.id);
			if (checked) {
				for (let i = 0; i < selected.value.length; i++) {
					if (selected.value[i].id == row.id) {
						selected.value.splice(i, 1);
						break;
					}
				}
			}
			tableRef.value!.toggleRowSelection(row, checked ? false : true);
		};
		return () => {
			return (
				<div class="tableList-module">
					{props.mode == "list" ? (
						<ElTable
							{...attrs}
							ref={tableRef}
							data={props.data}
							row-class-name={props.rowClass}
							onRow-click={(row: any) => rowClick(row)}
							onSelection-change={(list: any) => {
								selected.value = list;
								props.selectionChange?.(list);
							}}
							v-slots={{
								empty: () => {
									return slots.empty?.();
								}
							}}
						>
							{slots.default?.()}
						</ElTable>
					) : (
						<tableCard
							class="p-4"
							data={props.data}
							column={props.column}
							col={props.col}
							setting={props.setting}
							v-slots={props.cardSlot}
							selectionChange={props.selectionChange}
						></tableCard>
					)}
					{props.total ? (
						<ElPagination
							total={props.total}
							v-model:currentPage={data.pageIndex}
							v-model:pageSize={data.pageSize}
							{...props.pagination}
						/>
					) : null}
				</div>
			);
		};
	}
});
export default tableList;
